package com.jj.core.rpc;


import com.jj.config.Constants;
import com.jj.core.client.impl.ClientImpl;
import com.jj.core.client.impl.ClientManagerImpl;
import com.jj.net.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class RPCHandler {
    private static Logger logger = LoggerFactory.getLogger(RPCHandler.class);

    protected ThreadLocal<Context> contextThreadLocal = new ThreadLocal<>();
    protected RPCManager rpcManager = null;

    @Autowired
    protected ClientManagerImpl clientManager;

    public void setContext(Context context){
        contextThreadLocal.set(context);
    }

    public Context getContext(){
        return contextThreadLocal.get();
    }

    public void setManager(RPCManager rpcManager){
        this.rpcManager = rpcManager;
    };

    public RPCManager getManager(){
        return rpcManager;
    };

    public Long getClientId(){
        Context context = getContext();
        if(context != null){
            return (Long) context.getAttr(Constants.USER_ID_KEY);
        }
        return null;
    }

    public ClientImpl getClient(){
        Context context = getContext();
        if(context != null){
            Long uid = (Long) context.getAttr(Constants.USER_ID_KEY);
            ClientImpl client = (ClientImpl) clientManager.get(uid);
            if(client != null){
                return client;
            }
        }
        return null;
    }
}
